<!-- 试验构建_包括全局因素配置、想定级因素配置、模型级因素配置 -->
<template>
    <div class="experiment-build-container">
        <div class="experiment-build-container-top">
            <el-popover placement="bottom-end" width="500" @show="handleOnlineDesignShow" @hide="stopTimer" trigger="click">
                <el-table :data="tableData" style="width: 100%">
                    <el-table-column prop="name" label="名称" width="180">
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="90">
                    </el-table-column>
                    <el-table-column prop="runTime" label="运行时间" width="100">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button @click="handleContainerControlClick(scope.row)" type="text" size="small">{{
                                scope.row.status == "Running" ? "停止容器" : "启动容器" }}</el-button>
                            <el-button type="text" size="small" @click="handleConfigClick('onlineDesign')">进入</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-tag slot="reference" class="experiment-build-container-top_item">
                    <svg-icon icon-class="folder" width="14" height="14" />
                    <div class="title-word">{{ $t("tool.experimentDesign.onlineDesign") }}</div>
                </el-tag>
            </el-popover>
            <el-tag class="experiment-build-container-top_item" @click="handleConfigClick('intelligentAdvisor')">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.experimentDesign.intelligentAdvisor") }}</div>
            </el-tag>
            <div class="experiment-build-container-top_item" @click="$router.go(-1)">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.experimentDesign.return") }}</div>
            </div>
        </div>

        <div class="experiment-build-container-bottom">
            <!-- 左侧结构 -->
            <div class="e-b-left flex flex-col">
                <Tree ref="experimentDataTreeRef" :isGeneralFolderAndFile="true" :treeData="experimentDataList"
                    :folderMenu="right_menuList.rightMenuList_4" :fileMenu="right_menuList.rightMenuList_4"
                    @handleMenuClick="handleMenuClick" @nodeClick="nodeClick"></Tree>
            </div>

            <!-- 中间地图 -->
            <div class="e-b-middle">
                <MarsMap :url="configUrl" @onload="onMapload">
                </MarsMap>
            </div>

            <!-- 右侧智能参谋 -->
            <div class="e-b-right" v-if="showIntelligentAdvisor">
                <IntelligentAdvisor @close="closeIntelligentAdvisor"></IntelligentAdvisor>
            </div>
        </div>
    </div>
</template>
<script>
import { getScenarioTree } from "@/api/myspace/scenario-edit-tool/scenario-edit";
import Tree from "@/components/LeftTree/tree.vue";
import MarsMap from "@/views/common-components/mars-map.vue";
import IntelligentAdvisor from "./components/intelligent-advisor/intelligent-advisor.vue";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
let graphicLayer // 矢量图层对象
export default {
    name: "ScenarioBuild",
    data() {
        const basePathUrl = window.basePathUrl || ''
        return {
            configUrl: basePathUrl + '/config/map.json',
            showIntelligentAdvisor: false,
            experimentDataList: [],
            tableData: [{
                name: '测试试验-admin-09c2',
                status: 'Running',  // Stopped
                startingTime: '2025-06-09 09:09:09',
                runTime: '09:09:09'
            }],
            timer: null,
        };
    },
    props: {
        experimentId: {
            type: Number,
            default: 0,
        },
    },
    components: {
        Tree,
        MarsMap,
        IntelligentAdvisor,
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.experimentDesignTool.right_menuList,
            userId: (state) => state.user.id,
        }),
    },
    created() {
        this.getExperimentScenarioTree()
    },
    mounted() {
    },
    beforeDestroy() {
        graphicLayer.remove()
        graphicLayer = null
        // 组件销毁前清除定时器
        this.stopTimer();
    },

    methods: {
        getExperimentScenarioTree() {
            getScenarioTree().then((response) => {
                if (response.code === 200) {
                    this.experimentDataList = response.data[0].commonTreeList;
                }
            });
        },
        // 地图构造完成回调
        onMapload(map) {
            let _this = this;
            graphicLayer = new mars3d.layer.GraphicLayer()

            // 在layer上绑定监听事件
            graphicLayer.on(mars3d.EventType.click, function (event) {
                console.log("监听layer，单击了矢量对象", event)
                // _this.$refs["modelFactorConfig"].dialogVisible = true;
            })
            map.addLayer(graphicLayer);
            console.log("开始添加实体");
            // this.addEntity({ id: 1, nameChn: '实体1', sideId: 0 }, [132, 27, 10000], true)
            this.addDemoGraphic1()
            // this.addDemoGraphic2()
            // this.addDemoGraphic3()


        },
        addDemoGraphic1() {
            const graphic = new mars3d.graphic.ModelEntity({
                id: 1,
                name: "警车",
                position: [116.346929, 30.861947, 401.34],
                style: {
                    url: "https://data.mars3d.cn/gltf/mars/jingche/jingche.gltf",
                    scale: 20,
                    minimumPixelSize: 50,
                    heading: 90,

                    distanceDisplayCondition: true,
                    distanceDisplayCondition_near: 0,
                    distanceDisplayCondition_far: 10000,
                    distanceDisplayPoint: {
                        // 当视角距离超过一定距离(distanceDisplayCondition_far定义的) 后显示为点对象的样式
                        color: "#00ff00",
                        pixelSize: 12
                    },

                    label: {
                        text: "我是原始的",
                        font_size: 18,
                        color: "#ffffff",
                        pixelOffsetY: -50,
                        distanceDisplayCondition: true,
                        distanceDisplayCondition_far: 10000,
                        distanceDisplayCondition_near: 0
                    }
                },
                attr: { remark: "示例1" }
            })
            graphicLayer.addGraphic(graphic)
        },
        addDemoGraphic2() {
            const graphic = new mars3d.graphic.DivBoderLabel({
                position: [116.460722, 31.140888, 781],
                style: {
                    text: "火星科技Mars3D平台",
                    font_size: 15,
                    font_family: "微软雅黑",
                    color: "#ccc",
                    boderColor: "#15d1f2"
                },
                attr: { remark: "示例6" }
            })

            // 测试修改className
            graphic.on(mars3d.EventType.load, function (e) {
                graphic.addClass("className1")
                graphic.addClass("className2")

                setTimeout(() => {
                    graphic.removeClass("className1")
                }, 9000)
            })
            graphicLayer.addGraphic(graphic)
        },
        addDemoGraphic3() {
            const graphic = new mars3d.graphic.DivGraphic({
                position: [116.228043, 30.882207],
                style: {
                    html: `<div class="marsTiltPanel marsTiltPanel-theme-green">
                                <div class="marsTiltPanel-wrap">
                                    <div class="area">
                                        <div class="arrow-lt"></div>
                                        <div class="b-t"></div>
                                        <div class="b-r"></div>
                                        <div class="b-b"></div>
                                        <div class="b-l"></div>
                                        <div class="arrow-rb"></div>
                                        <div class="label-wrap">
                                            <div class="title">大别山水厂</div>
                                            <div class="label-content">
                                                <div class="data-li">
                                                    <div class="data-label">实时流量：</div>
                                                    <div class="data-value"><span class="label-num">99</span><span class="label-unit">m³/s</span>
                                                    </div>
                                                </div>
                                                <div class="data-li">
                                                    <div class="data-label">水池液位：</div>
                                                    <div class="data-value"><span class="label-num">20.02</span><span class="label-unit">m</span>
                                                    </div>
                                                </div>
                                                <div class="data-li">
                                                    <div class="data-label">水泵状态：</div>
                                                    <div class="data-value"><span class="label-tag data-value-status-1" title="中间状态">1号</span><span
                                                            class="label-tag data-value-status-0" title="关闭状态">2号</span></div>
                                                </div>
                                                <div class="data-li">
                                                    <div class="data-label">出水阀门：</div>
                                                    <div class="data-value"><span class="label-tag data-value-status-1" title="中间状态">1号</span><span
                                                            class="label-tag data-value-status-2" title="打开状态">2号</span></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="b-t-l"></div>
                                    <div class="b-b-r"></div>
                                </div>
                                <div class="arrow" ></div>
                            </div>`,
                    horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 200000), // 按视距距离显示
                    // scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 200000, 0.2),
                    clampToGround: false
                },
                attr: { remark: "示例10" },
                // 可以传入自定义测试点样式
                // testPoint: {
                //   color: '#ff0000',
                //   pixelSize: 8,
                // },
                pointerEvents: false // false时不允许拾取和触发任意鼠标事件，但可以穿透div缩放地球
            })
            graphicLayer.addGraphic(graphic)

            graphic.testPoint = true // 打开测试点，与DIV点进行对比位置调整css
        },
        /** 添加实体 */
        addEntity(item, position, isVisible) {
            var pathEntity = new mars3d.graphic.PathEntity({
                id: item.id,
                position: position,
                show: isVisible,
                attr: item,
                maxCacheCount: 50,
                style: {
                    show: false,
                    resolution: 1,
                    leadTime: 0,
                    // trailTime: 10,
                    material: new Cesium.PolylineGlowMaterialProperty({
                        glowPower: 0.1,
                        taperPower: 0.5,
                        color: Cesium.Color.AQUA,
                    }),
                    width: 5,
                },
                model: {
                    uri: './FJ.glb',
                    minimumPixelSize: 50,
                    scale: 1000,
                    show: true,
                    runAnimations: true,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        0,
                        15000000
                    ), // 按视距距离显示
                },
                label: {
                    text: item.nameChn,
                    font_size: 15,
                    font_family: "黑体",
                    color: item.sideId == 0 ? "#FF5C5C" : "#84B5FF",
                    outline: false,
                    outlineColor: "#f1f1f1",
                    outlineWidth: 1,
                    background: true,
                    backgroundColor: "#000000",
                    backgroundOpacity: 0,
                    hasPixelOffset: true,
                    pixelOffsetY: -23,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        0,
                        8000000
                    ), // 按视距距离显示
                },
                point: {
                    color: item.sideId == 0 ? "#FF4242" : "#2979FF",
                    pixelSize: 10,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        15000000,
                        Number.MAX_VALUE
                    ), // 按视距距离显示
                },
            });
            graphicLayer.addGraphic(pathEntity);
        },

        // 处理容器控制点击
        handleContainerControlClick(row) {
            console.log('容器控制点击', row);
        },

        nodeClick(node) {
            this.selectedNodeInfo = node;
            // 下面这三个赋值是用于点击[去编辑该数据模型]按钮时，让节点展开并选中
            // this.defaultExpandedKeys = Array.from(new Set([...this.defaultExpandedKeys, node.id]))
            // this.currentNodeKey = node.id;
            // this.$refs.scenarioBuildTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
        },


        // 菜单点击
        handleMenuClick() {

        },

        formatDuration(startTime) {
            // 1. 获取当前时间和开始时间的时间戳（毫秒）
            const now = new Date();
            const start = new Date(startTime);
            const diffMs = now - start; // 时间差（毫秒）

            // 2. 计算小时、分钟、秒
            const diffSeconds = Math.floor(diffMs / 1000);
            const hours = Math.floor(diffSeconds / 3600);
            const minutes = Math.floor((diffSeconds % 3600) / 60);
            const seconds = diffSeconds % 60;

            // 3. 格式化为 00:00:00
            return [
                hours.toString().padStart(2, '0'),
                minutes.toString().padStart(2, '0'),
                seconds.toString().padStart(2, '0')
            ].join(':');
        },

        // 点击在线设计按钮，popover显示的回调
        handleOnlineDesignShow() {
            this.stopTimer();
            this.timer = setInterval(() => {
                this.tableData[0].runTime = this.formatDuration(this.tableData[0].startingTime)
                console.log("调用", this.tableData[0].runTime);
            }, 1000)
        },

        stopTimer() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
        },

        // 处理配置的点击
        handleConfigClick(configName) {
            if (configName == 'intelligentAdvisor') {
                this.showIntelligentAdvisor = true;
                return;
            }
            if (configName == 'onlineDesign') {
                window.open('http://192.168.1.109:3000');
            }
        },

        // 关闭智能参谋窗口
        closeIntelligentAdvisor() {
            console.log("guanboi");
            this.showIntelligentAdvisor = false;
        }
    }

};
</script>

<style lang="scss" scoped>
.experiment-build-container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;

    .experiment-build-container-top {
        height: 35px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        border-bottom: 1px solid var(--ui-border-color-base);

        .experiment-build-container-top_item {
            display: flex;
            margin-right: 20px;
            align-items: center;
            font-size: var(--ui-font-size-base);
            cursor: pointer;

            .title-word {
                margin-left: 5px;
            }
        }
    }

    .experiment-build-container-bottom {
        display: flex;
        height: calc(100% - 35px);
        padding: 0 0 0 10px;

        .e-b-left {
            width: 300px;
            height: 100%;
            display: flex;
            padding: 10px 10px 0 0;
            border-right: 1px solid var(--ui-border-color-split);

            ::v-deep .el-table__row {
                height: 42px;
            }

            ::v-deep .el-table-column--selection .cell {
                padding-left: 10px;
            }

            ::v-deep .el-table__expanded-cell {
                padding-left: 20px;
            }

            ::v-deep .el-table__body {
                width: 100% !important;
            }

        }

        .e-b-middle {
            flex: 1;
            min-width: 450px;
            height: 100%;
        }

        .e-b-right {
            width: 400px;
            height: calc(100% - 66px);
            border-left: 1px solid var(--ui-border-color-split);
        }
    }

}
</style>